package com.meilai.project.service.business.dataLevel.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.business.dataLevel.DataLevelDTO;
import com.meilai.project.dto.business.dataLevel.DataLevelRemoveDTO;
import com.meilai.project.entity.business.dataLevel.DataQueryBusiness;
import com.meilai.project.entity.business.dataLevel.DataQueryBusinessLevel;
import com.meilai.project.entity.business.dataLevel.LevelRoleRelation;
import com.meilai.project.entity.business.dataLevel.LevelUserRelation;
import com.meilai.project.entity.personnel.org.Role;
import com.meilai.project.entity.system.User;
import com.meilai.project.entity.system.UserRoleRelation;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.dataLevel.DataQueryBusinessLevelMapper;
import com.meilai.project.service.business.dataLevel.DataQueryBusinessLevelService;
import com.meilai.project.service.business.dataLevel.DataQueryBusinessService;
import com.meilai.project.service.business.dataLevel.LevelRoleRelationService;
import com.meilai.project.service.business.dataLevel.LevelUserRelationService;
import com.meilai.project.service.personnel.org.RoleService;
import com.meilai.project.service.system.UserRoleRelationService;
import com.meilai.project.service.system.UserService;
import com.meilai.project.vo.business.dataLevel.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务等级表 服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-09-21
 */
@Service
public class DataQueryBusinessLevelServiceImpl extends ServiceImpl<DataQueryBusinessLevelMapper, DataQueryBusinessLevel> implements DataQueryBusinessLevelService {

    @Autowired
    private DataQueryBusinessService dataQueryBusinessService;

    @Autowired
    private LevelRoleRelationService levelRoleRelationService;

    @Autowired
    private LevelUserRelationService levelUserRelationService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleRelationService userRoleRelationService;


    @Override
    public List<DataLevelVO> queryDataLevelVOList() {
        List<DataQueryBusiness> list = dataQueryBusinessService.list(Wrappers.<DataQueryBusiness>lambdaQuery().isNull(DataQueryBusiness::getDeleted_at));
        List<DataLevelVO> result_list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> collect = list.stream().map(DataQueryBusiness::getCode).collect(Collectors.toList());
            // 查询等级数据
            List<DataQueryBusinessLevel> level_list = this.list(Wrappers.<DataQueryBusinessLevel>lambdaQuery().in(DataQueryBusinessLevel::getBusiness_code, collect));
            // 整理出不同业务对应的等级数据map
            Map<String, List<DataQueryBusinessLevel>> level_map = level_list.stream().collect(Collectors.groupingBy(DataQueryBusinessLevel::getBusiness_code));
            // 查询出不同的等级关联的角色的数据并整理成map
            Set<Long> level_ids = level_list.stream().map(DataQueryBusinessLevel::getId).collect(Collectors.toSet());
            Map<Long, List<LevelRoleRelation>> level_role_relation_map = levelRoleRelationService.list(Wrappers.<LevelRoleRelation>lambdaQuery().in(LevelRoleRelation::getLevel_id, level_ids)).stream().collect(Collectors.groupingBy(LevelRoleRelation::getLevel_id));
            Map<Long, List<LevelUserRelation>> level_user_relation_map = levelUserRelationService.list(Wrappers.<LevelUserRelation>lambdaQuery().in(LevelUserRelation::getLevel_id, level_ids)).stream().collect(Collectors.groupingBy(LevelUserRelation::getLevel_id));
            // 查询所有的用户
            List<User> user_list = userService.list(Wrappers.<User>lambdaQuery().isNull(User::getDeleted_at).eq(User::getStatus, 1));
            Map<Long, User> user_map = user_list.stream().collect(Collectors.toMap(User::getId, user -> user));
            // 查询用户关联的角色数据
            List<UserRoleRelation> user_role_relation_list = userRoleRelationService.list(Wrappers.<UserRoleRelation>lambdaQuery().in(UserRoleRelation::getUser_id, user_map.keySet()));
            // 整理出用户和角色的关联数据map
            Map<Long, List<UserRoleRelation>> user_role_map = user_role_relation_list.stream().collect(Collectors.groupingBy(UserRoleRelation::getUser_id));
//            // 整理出角色ids
//            Set<Long> role_ids = user_role_relation_list.stream().map(UserRoleRelation::getRole_id).collect(Collectors.toSet());
            // 查询出角色数据
            List<Role> role_list = roleService.list(Wrappers.<Role>lambdaQuery().isNull(Role::getDeleted_at).eq(Role::getStatus, 1));
            // 整理出角色map
            Map<Long, Role> role_map = role_list.stream().collect(Collectors.toMap(Role::getId, role -> role));
            list.forEach(item -> {
                DataLevelVO dataLevelVO = new DataLevelVO();
                dataLevelVO.setId(item.getId());
                dataLevelVO.setCode(item.getCode());
                dataLevelVO.setName(item.getName());
                List<LevelVO> levelVOList = new ArrayList<>();
                List<Long> hasLevelUserIds = new ArrayList<>();
                // 处理等级数据
                if (level_map.containsKey(item.getCode())) {
                    List<DataQueryBusinessLevel> levelList = level_map.get(item.getCode());
                    List<LevelUserRelation> business_user_leve_relation_list = new ArrayList<>();
                    List<LevelRoleRelation> business_role_leve_relation_list = new ArrayList<>();
                    levelList.forEach(level -> {
                        business_role_leve_relation_list.addAll(level_role_relation_map.getOrDefault(level.getId(), new ArrayList<>()));
                        business_user_leve_relation_list.addAll(level_user_relation_map.getOrDefault(level.getId(), new ArrayList<>()));
                    });
                    List<BusinessLevelVO> businessLevelVOS = this.queryUserMaxLevel(business_role_leve_relation_list, business_user_leve_relation_list, user_role_map, levelList, new ArrayList<>(user_map.keySet()));
                    levelList.forEach(level -> {
                        LevelVO levelVO = new LevelVO();
                        levelVO.setId(level.getId());
                        levelVO.setLevel(level.getLevel());
                        List<RoleLevelVO> roleLevelVOList = new ArrayList<>();
                        // 处理等级关联的角色信息
                        if (level_role_relation_map.containsKey(level.getId())) {
                            List<LevelRoleRelation> roleRelationList = level_role_relation_map.get(level.getId());
                            roleRelationList.forEach(role -> {
                                RoleLevelVO roleLevelVO = new RoleLevelVO();
                                roleLevelVO.setId(role.getRole_id());
                                if (role_map.containsKey(role.getRole_id())) {
                                    roleLevelVO.setRole_name(role_map.get(role.getRole_id()).getName());
                                } else {
                                    roleLevelVO.setRole_name("未知角色");
                                }
                                roleLevelVOList.add(roleLevelVO);
                            });
                        }
                        List<UserLevelVO> userLevelVOList = new ArrayList<>();
                        // 处理等级关联的用户数据
                        List<BusinessLevelVO> businessLevelVOList = businessLevelVOS.stream().filter(tmp -> tmp.getLevel().equals(level.getLevel())).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(businessLevelVOList)) {
                            businessLevelVOList = businessLevelVOList.stream().sorted(Comparator.comparing(BusinessLevelVO::getSource_type)).collect(Collectors.toList());
                            businessLevelVOList.forEach(businessLevelVO -> {
                                UserLevelVO userLevelVO = new UserLevelVO();
                                if (user_map.containsKey(businessLevelVO.getUser_id())) {
                                    userLevelVO.setUser_name(user_map.get(businessLevelVO.getUser_id()).getName());
                                } else {
                                    userLevelVO.setUser_name("未知用户");
                                }
                                userLevelVO.setId(businessLevelVO.getUser_id());
                                userLevelVO.setCan_remove(businessLevelVO.getSource_type() == 2);
                                userLevelVOList.add(userLevelVO);
                                hasLevelUserIds.add(businessLevelVO.getUser_id());
                            });
                        }
                        levelVO.setRoleLevelVOList(roleLevelVOList);
                        levelVO.setUserLevelVOList(userLevelVOList);
                        levelVOList.add(levelVO);
                    });
                }
                dataLevelVO.setLevelVOList(levelVOList);
                List<UserLevelVO> noLevelUserList = user_list.stream().filter(user -> !hasLevelUserIds.contains(user.getId())).map(user -> {
                    UserLevelVO userLevelVO = new UserLevelVO();
                    userLevelVO.setCan_remove(false);
                    userLevelVO.setUser_name(user.getName());
                    userLevelVO.setId(user.getId());
                    return userLevelVO;
                }).collect(Collectors.toList());
                dataLevelVO.setNoLevelUserList(noLevelUserList);
                result_list.add(dataLevelVO);
            });
        }
        return result_list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveLevel(DataLevelDTO dto) {
        DataQueryBusinessLevel level = new DataQueryBusinessLevel();
        level.setBusiness_code(dto.getCode());
        // 先查询等级数据
        List<DataQueryBusinessLevel> list = this.list(Wrappers.<DataQueryBusinessLevel>lambdaQuery().eq(DataQueryBusinessLevel::getBusiness_code, dto.getCode()).orderByDesc(DataQueryBusinessLevel::getLevel));
        if (CollectionUtils.isNotEmpty(list)) {
            Integer businessLevel = list.get(0).getLevel();
            level.setLevel(businessLevel + 1);
        } else {
            level.setLevel(1);
        }
        // 保存等级数据
        this.save(level);
        // 保存等级的角色数据
        if (CollectionUtils.isNotEmpty(dto.getRole_list())) {
            levelRoleRelationService.saveBatch(dto.getRole_list().stream().map(item -> {
                LevelRoleRelation levelRoleRelation = new LevelRoleRelation();
                levelRoleRelation.setLevel_id(level.getId());
                levelRoleRelation.setRole_id(item);
                return levelRoleRelation;
            }).collect(Collectors.toList()));
        }
        // 保存等级的用户数据
        if (CollectionUtils.isNotEmpty(dto.getUser_list())) {
            levelUserRelationService.saveBatch(dto.getUser_list().stream().map(item -> {
                LevelUserRelation levelUserRelation = new LevelUserRelation();
                levelUserRelation.setLevel_id(level.getId());
                levelUserRelation.setUser_id(item);
                return levelUserRelation;
            }).collect(Collectors.toList()));
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addLevelRole(DataLevelDTO dto) {
        DataQueryBusinessLevel level = this.checkLevel(dto.getCode(), dto.getLevel());
        // 保存等级的角色数据
        if (CollectionUtils.isNotEmpty(dto.getRole_list())) {
            levelRoleRelationService.saveBatch(dto.getRole_list().stream().map(item -> {
                LevelRoleRelation levelRoleRelation = new LevelRoleRelation();
                levelRoleRelation.setLevel_id(level.getId());
                levelRoleRelation.setRole_id(item);
                return levelRoleRelation;
            }).collect(Collectors.toList()));
        }
        return true;
    }

    @Override
    public List<Role> queryCanAddRoleList(String code, Integer level) {
        DataQueryBusinessLevel businessLevel = this.checkLevel(code, level);
        List<LevelRoleRelation> roleRelationList = levelRoleRelationService.list(Wrappers.<LevelRoleRelation>lambdaQuery().eq(LevelRoleRelation::getLevel_id, businessLevel.getId()));
        Set<Long> collect = roleRelationList.stream().map(LevelRoleRelation::getRole_id).collect(Collectors.toSet());
        List<Role> roleList = roleService.list(Wrappers.<Role>lambdaQuery().isNull(Role::getDeleted_at).eq(Role::getStatus, 1));
        roleList.removeIf(next -> collect.contains(next.getId()));
        return roleList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addLevelUser(DataLevelDTO dto) {
        DataQueryBusinessLevel level = this.checkLevel(dto.getCode(), dto.getLevel());
        // 保存等级的用户数据
        if (CollectionUtils.isNotEmpty(dto.getUser_list())) {
            levelUserRelationService.saveBatch(dto.getUser_list().stream().map(item -> {
                LevelUserRelation levelUserRelation = new LevelUserRelation();
                levelUserRelation.setLevel_id(level.getId());
                levelUserRelation.setUser_id(item);
                return levelUserRelation;
            }).collect(Collectors.toList()));
        }
        return true;
    }

    @Override
    public Boolean removeLevelUser(DataLevelRemoveDTO dto) {
        DataQueryBusinessLevel level = this.checkLevel(dto.getCode(), dto.getLevel());
        return levelUserRelationService.remove(Wrappers.<LevelUserRelation>lambdaQuery().eq(LevelUserRelation::getLevel_id, level.getId()).eq(LevelUserRelation::getUser_id, dto.getId()));
    }

    @Override
    public Boolean removeLevelRole(DataLevelRemoveDTO dto) {
        DataQueryBusinessLevel level = this.checkLevel(dto.getCode(), dto.getLevel());
        return levelRoleRelationService.remove(Wrappers.<LevelRoleRelation>lambdaQuery().eq(LevelRoleRelation::getLevel_id, level.getId()).eq(LevelRoleRelation::getRole_id, dto.getId()));
    }

    private DataQueryBusinessLevel checkLevel(String code, Integer level_num) {
        if (StringUtils.isEmpty(code)) {
            throw new CommonException("业务编码不能为空");
        }
        if (level_num == null) {
            throw new CommonException("等级级别不能为空");
        }
        DataQueryBusinessLevel level = this.getOne(Wrappers.<DataQueryBusinessLevel>lambdaQuery().eq(DataQueryBusinessLevel::getBusiness_code, code).eq(DataQueryBusinessLevel::getLevel, level_num));
        if (level == null) {
            throw new CommonException("等级数据不存在");
        }
        return level;
    }

    @Override
    public int getUserMaxLevel(String code, Long user_id) {
        if (StringUtils.isEmpty(code)) {
            throw new CommonException("业务编码不能为空");
        }
        if (user_id == null) {
            throw new CommonException("用户id不能为空");
        }
        DataQueryBusiness one = dataQueryBusinessService.getOne(Wrappers.<DataQueryBusiness>lambdaQuery().isNull(DataQueryBusiness::getDeleted_at).eq(DataQueryBusiness::getCode, code));
        if (one == null) {
            throw new CommonException("业务不存在");
        }
        if (one.getStatus() == 0) {
            throw new CommonException("业务被禁用");
        }
        List<DataQueryBusinessLevel> levelList = this.list(Wrappers.<DataQueryBusinessLevel>lambdaQuery().eq(DataQueryBusinessLevel::getBusiness_code, code));
        if (CollectionUtils.isEmpty(levelList)) {
            throw new CommonException("业务下面没有等级数据");
        }
        DataQueryBusinessLevel minimumLevel = levelList.stream().sorted(Comparator.comparing(DataQueryBusinessLevel::getLevel, Comparator.reverseOrder())).collect(Collectors.toList()).get(0);
        List<Long> level_ids = levelList.stream().map(DataQueryBusinessLevel::getId).collect(Collectors.toList());
        List<LevelRoleRelation> levelRoleRelationList = levelRoleRelationService.list(Wrappers.<LevelRoleRelation>lambdaQuery().in(LevelRoleRelation::getLevel_id, level_ids));
        List<LevelUserRelation> levelUserRelationList = levelUserRelationService.list(Wrappers.<LevelUserRelation>lambdaQuery().in(LevelUserRelation::getLevel_id, level_ids));
        List<UserRoleRelation> userRoleRelationList = userRoleRelationService.list(Wrappers.<UserRoleRelation>lambdaQuery().eq(UserRoleRelation::getUser_id, user_id));
        // 该用户在等级关联中最大的等级数据
        Set<Long> user_level_ids = levelUserRelationList.stream().filter(item -> user_id.equals(item.getUser_id())).map(LevelUserRelation::getLevel_id).collect(Collectors.toSet());
        List<DataQueryBusinessLevel> levelListByUserRelation = levelList.stream().filter(item -> user_level_ids.contains(item.getId())).sorted(Comparator.comparing(DataQueryBusinessLevel::getLevel)).collect(Collectors.toList());
        BusinessLevelVO userRelationLevelVO = null;
        if (CollectionUtils.isNotEmpty(levelListByUserRelation)) {
            userRelationLevelVO = new BusinessLevelVO();
            userRelationLevelVO.setLevel(levelListByUserRelation.get(0).getLevel());
            userRelationLevelVO.setSource_type(2);
            userRelationLevelVO.setUser_id(user_id);
        }
        // 如果用户没有关联角色
        if (CollectionUtils.isNotEmpty(userRoleRelationList)) {
            Set<Long> role_ids = userRoleRelationList.stream().map(UserRoleRelation::getRole_id).collect(Collectors.toSet());
            Set<Long> level_set = levelRoleRelationList.stream().filter(item -> role_ids.contains(item.getRole_id())).map(LevelRoleRelation::getLevel_id).collect(Collectors.toSet());
            List<DataQueryBusinessLevel> levelListByRoleRelation = levelList.stream().filter(item -> level_set.contains(item.getId())).sorted(Comparator.comparing(DataQueryBusinessLevel::getLevel)).collect(Collectors.toList());
            // 如果等级没有关联角色
            if (CollectionUtils.isNotEmpty(levelListByRoleRelation)) {
                BusinessLevelVO roleRelationLevelVO = new BusinessLevelVO();
                roleRelationLevelVO.setLevel(levelListByRoleRelation.get(0).getLevel());
                roleRelationLevelVO.setSource_type(1);
                roleRelationLevelVO.setUser_id(user_id);
                if (userRelationLevelVO == null) {
                    return roleRelationLevelVO.getLevel();
                } else {
                    if (userRelationLevelVO.getLevel() <= roleRelationLevelVO.getLevel()) {
                        return userRelationLevelVO.getLevel();
                    } else {
                        return roleRelationLevelVO.getLevel();
                    }
                }
            } else {
                if (userRelationLevelVO != null) {
                    return userRelationLevelVO.getLevel();
                } else {
                    // todo 如果是无级别的用户则使用最低的等级
                    return minimumLevel.getLevel();
                }
            }
        } else {
            if (userRelationLevelVO != null) {
                return userRelationLevelVO.getLevel();
            } else {
                // todo 如果是无级别的用户则使用最低的等级
                return minimumLevel.getLevel();
            }
        }
    }


    /**
     * 查询每个用户对应的等级信息
     *
     * @param levelRoleRelationList  等级关联角色集合 来源于同一个业务的数据
     * @param levelUserRelationList  等级关联用户的集合 来源于同一个业务的数据
     * @param user_role_relation_map 用户对应的用户关系map 根据user_ids中的用户ids出来
     * @param levelList              等级集合 来源于同一个业务的数据
     * @param user_ids               用户集合
     * @return 每个用户对应的最大等级数据
     *  todo 注：如果用户在此业务中没有等级 会返回空的集合
     */
    private List<BusinessLevelVO> queryUserMaxLevel(List<LevelRoleRelation> levelRoleRelationList, List<LevelUserRelation> levelUserRelationList, Map<Long, List<UserRoleRelation>> user_role_relation_map, List<DataQueryBusinessLevel> levelList, List<Long> user_ids) {
        List<BusinessLevelVO> result_list = new ArrayList<>();
        user_ids.forEach(user_id -> {
            List<BusinessLevelVO> businessLevelVOList = new ArrayList<>();
            BusinessLevelVO userRelationLevelVO = null;
            // 该用户在等级关联中最大的等级数据
            Set<Long> level_ids = levelUserRelationList.stream().filter(item -> user_id.equals(item.getUser_id())).map(LevelUserRelation::getLevel_id).collect(Collectors.toSet());
            List<DataQueryBusinessLevel> levelListByUserRelation = levelList.stream().filter(item -> level_ids.contains(item.getId())).sorted(Comparator.comparing(DataQueryBusinessLevel::getLevel)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(levelListByUserRelation)) {
                userRelationLevelVO = new BusinessLevelVO();
                userRelationLevelVO.setLevel(levelListByUserRelation.get(0).getLevel());
                userRelationLevelVO.setSource_type(2);
                userRelationLevelVO.setUser_id(user_id);
            }
            if (user_role_relation_map.containsKey(user_id)) {
                Set<Long> role_ids = user_role_relation_map.get(user_id).stream().map(UserRoleRelation::getRole_id).collect(Collectors.toSet());
                Set<Long> level_set = levelRoleRelationList.stream().filter(item -> role_ids.contains(item.getRole_id())).map(LevelRoleRelation::getLevel_id).collect(Collectors.toSet());
                List<DataQueryBusinessLevel> levelListByRoleRelation = levelList.stream().filter(item -> level_set.contains(item.getId())).sorted(Comparator.comparing(DataQueryBusinessLevel::getLevel)).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(levelListByRoleRelation)) {
                    BusinessLevelVO roleRelationLevelVO = new BusinessLevelVO();
                    roleRelationLevelVO.setLevel(levelListByRoleRelation.get(0).getLevel());
                    roleRelationLevelVO.setSource_type(1);
                    roleRelationLevelVO.setUser_id(user_id);
                    if (userRelationLevelVO == null) {
                        businessLevelVOList.add(roleRelationLevelVO);
                    } else {
                        if (userRelationLevelVO.getLevel() <= roleRelationLevelVO.getLevel()) {
                            businessLevelVOList.add(userRelationLevelVO);
                        } else {
                            businessLevelVOList.add(roleRelationLevelVO);
                        }
                    }
                } else {
                    if (userRelationLevelVO != null) {
                        businessLevelVOList.add(userRelationLevelVO);
                    }
                }
            }
            result_list.addAll(businessLevelVOList);
        });
        return result_list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeLevel(String code, Integer level) {
        return true;
    }

    @Override
    public List<LevelUserVO> queryLevelUserVO(String code) {
        if (StringUtils.isEmpty(code)) {
            throw new CommonException("code不能空");
        }
        DataQueryBusiness one = dataQueryBusinessService.getOne(Wrappers.<DataQueryBusiness>lambdaQuery().eq(DataQueryBusiness::getCode, code));
        if (one == null) {
            throw new CommonException("数据业务不存在");
        }
        // 查询等级数据
        List<DataQueryBusinessLevel> level_list = this.list(Wrappers.<DataQueryBusinessLevel>lambdaQuery().eq(DataQueryBusinessLevel::getBusiness_code, code));
        List<Long> level_ids = level_list.stream().map(DataQueryBusinessLevel::getId).collect(Collectors.toList());
        List<LevelUserRelation> business_user_leve_relation_list = levelUserRelationService.list(Wrappers.<LevelUserRelation>lambdaQuery().in(LevelUserRelation::getLevel_id, level_ids));
        List<LevelRoleRelation> business_role_leve_relation_list = levelRoleRelationService.list(Wrappers.<LevelRoleRelation>lambdaQuery().in(LevelRoleRelation::getLevel_id, level_ids));
        // 查询所有的用户
        List<User> user_list = userService.list(Wrappers.<User>lambdaQuery().isNull(User::getDeleted_at).eq(User::getStatus, 1));
        Map<Long, User> user_map = user_list.stream().collect(Collectors.toMap(User::getId, user -> user));
        // 查询用户关联的角色数据
        List<UserRoleRelation> user_role_relation_list = userRoleRelationService.list(Wrappers.<UserRoleRelation>lambdaQuery().in(UserRoleRelation::getUser_id, user_map.keySet()));
        // 整理出用户和角色的关联数据map
        Map<Long, List<UserRoleRelation>> user_role_map = user_role_relation_list.stream().collect(Collectors.groupingBy(UserRoleRelation::getUser_id));
        List<BusinessLevelVO> businessLevelVOS = this.queryUserMaxLevel(business_role_leve_relation_list, business_user_leve_relation_list, user_role_map, level_list, new ArrayList<>(user_map.keySet()));
        Map<String, List<User>> map = new HashMap<>();
        List<Long> hasLevelUserIds = new ArrayList<>();
        businessLevelVOS.forEach(item -> {
            String key = item.getLevel().toString();
            hasLevelUserIds.add(item.getUser_id());
            if (map.containsKey(key)) {
                map.get(key).add(user_map.get(item.getUser_id()));
            } else {
                List<User> userList = new ArrayList<>();
                userList.add(user_map.get(item.getUser_id()));
                map.put(key, userList);
            }
        });
        List<User> noLevelUserList = user_list.stream().filter(user -> !hasLevelUserIds.contains(user.getId())).collect(Collectors.toList());
        List<LevelUserVO> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(noLevelUserList)) {
            LevelUserVO levelUserVO = new LevelUserVO();
            levelUserVO.setLevel("无级别用户");
            levelUserVO.setUserList(noLevelUserList);
            levelUserVO.setSort(0);
            list.add(levelUserVO);
        }
        if (!map.isEmpty()) {
            map.forEach((key, value) -> {
                LevelUserVO levelUserVO = new LevelUserVO();
                levelUserVO.setLevel(key + "级");
                levelUserVO.setUserList(value);
                levelUserVO.setSort(Integer.parseInt(key));
                list.add(levelUserVO);
            });
        }
        return list.stream().sorted(Comparator.comparing(LevelUserVO::getSort)).collect(Collectors.toList());
    }
}
